/**
 * 针对基础计算 切换CPU测试
 * @file cpuAffinity.c
 * @author your name (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2022-04-08
 * 
 * @copyright Copyright (c) 2022
 * 
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>


/* Return the UNIX time in microseconds */
long long ustime(void) {
    struct timeval tv;
    long long ust;

    gettimeofday(&tv, NULL);
    ust = ((long long)tv.tv_sec)*1000000;
    ust += tv.tv_usec;
    return ust;
}

void loopfunc(int c){    
    for(int i = 0;i< 999999999; i++){
        c++;
    }
    printf("%d\n", c);
}

int main(int argc, char* argv[]){
    if(argc != 4){
        printf("usage: perf stat ./a.out m n loop\n");
        printf("m: 起始CPU编号，如0\n");
        printf("m: 结束CPU编号，如63\n");
        printf("loop: 循环次数，如100\n");
        return 1;
    }

    int data = 1;
    long long t0, t1;
    char cmd[64] = {0};
    int m,n,loop;
    m = atoi(argv[1]);
    n = atoi(argv[2]);
    loop = atoi(argv[3]);

    pid_t pid = getpid();   
    for(int i = m;i<=n;i++){
        memset(cmd, 0, sizeof(cmd));
        sprintf(cmd, "taskset -p --cpu-list %d %d > /dev/null 2>&1\n", i, pid);
        //printf("exec %s\n", cmd);
        printf("CPU%d,", i);
        system(cmd);

        for(int j = 0;j< loop;j++){
            t0 = ustime();            
            loopfunc(loop);
            t1 = ustime();
            printf("%6f,", (t1-t0)/1000000.0f);
            fflush(stdout);            
        }        
        printf("\n");
    }
    return 0;
}